package br.unesp.rc.lista01.ex_03.dao;

import java.util.ArrayList;
import java.util.List;

import br.unesp.rc.lista01.ex_03.beans.Alerta;

import com.db4o.Db4oEmbedded;
import com.db4o.ObjectContainer;
import com.db4o.ObjectSet;
import com.db4o.ext.Db4oException;

public class AlertaDAOImp implements AlertaDAO {

	public AlertaDAOImp() {
		
	}
	
	public boolean addAlerta(Alerta alerta) {
		ObjectContainer db = Db4oEmbedded.openFile(Db4oEmbedded.newConfiguration(), "database.db4o");
		try {
			db.store(alerta);
		} catch (Db4oException e) {
			throw new RuntimeException(e);
		} finally {
			db.close();
		}
		return true;
	}
	
	public boolean removeAlerta(Alerta alerta) {
		ObjectContainer db = Db4oEmbedded.openFile(Db4oEmbedded.newConfiguration(), "database.db4o");
		try {
			db.delete(alerta);
		} catch (Db4oException e) {
			throw new RuntimeException(e);
		} finally {
			db.close();
		}
		return true;
	}
	
	public List<Alerta> getAlertas() {
		ObjectContainer db = Db4oEmbedded.openFile(Db4oEmbedded.newConfiguration(), "database.db4o");
		List<Alerta> alertas = new ArrayList<Alerta>();
        try {
        	ObjectSet<Alerta> objects = db.query(Alerta.class);
        	for (Alerta alerta: objects) {
        		alertas.add(alerta);
        	}
        } catch (Db4oException e) {
			throw new RuntimeException(e);
		} finally {
			db.close();
		}
        return alertas;
	}

}
